<?php

namespace addons\mental\controller;

use addons\mental\model\WxUser;
use app\common\library\Sms;
use app\common\library\Ims;
use fast\Random;
use think\Hook;
use think\Validate;
use addons\mental\model\Testlog;
use think\Config;
use think\Session;
use think\Db;
use think\Cache;
use think\Log;

class User extends Base
{
    protected $noNeedLogin = ['mobilelogin', 'authLogin'];

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $wx_user_id = Session::get('wx_user_id');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            //绑定到wxUser
            $wxUser = new WxUser();
            $wx_user = $wxUser->where(['id' => $wx_user_id])->find();
            $userinfo = $this->auth->getUserinfo();
            if ($wx_user) {
                $wx_user->user_id = $this->auth->id;
                $wx_user->save();
                //更新下昵称
                if (empty($userinfo['avatar']) || empty($userinfo['nickname'])) {
                    $userObj = $this->auth->getUser();
                    $userObj->nickname = $wx_user->nickname;
                    $userObj->avatar = $wx_user->avatar;
                    $userObj->save();
                }
            }
            $data = ['userinfo' => $userinfo];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * Undocumented function
     * 个人信息
     * @return void
     */
    public function myinfo()
    {
        $userInfo = $this->auth->getUserinfo();
//        $userInfo['avatar'] = cdnurl($userInfo['avatar'], true);
        $testlog = new Testlog();
//        $userInfo['finish_num'] = $testlog->where('user_id', '=', $this->auth->id)->where('status', '=', 'finish')->count();
//        $userInfo['unfinish_num'] = $testlog->where('user_id', '=', $this->auth->id)->where('status', '=', 'unfinish')->count();
        $this->success(__('Operation completed'), $userInfo);
    }

    /**
     * Undocumented function
     * 修改用户信息
     * @return void
     */
    public function update_info()
    {   
        // applet 小程序
        $access_token = Cache::get("applet_access_token");
        if(!$access_token){
            $appId = 'wx170fe8ce2ce8c283';
            $appSecret = 'ae6c0d43a4f5d6ee537f41136dd01219';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
            $data = json_decode(getJson($url),true);
            Log::info('token:'.json_encode($data,true));
            if(isset($data['access_token']) && $data['access_token'] != ''){
                Cache::rm("applet_access_token");
                Cache::set("applet_access_token",$data['access_token'],7000);
                $access_token=$data['access_token'];
            }
            Log::info('redis_official:'.$access_token);
        }
        $openid = Db::name('user')->where('id',$this->auth->id)->value('openid');
        $avatar = $this->request->post('avatar');
        $nickname = $this->request->post('nickname');

        $ret = send_post($access_token,$nickname,$openid);
        $data = json_decode($ret,true);
        if($data['result']['label']!=100){
            $this->error('昵称存在敏感信息');
        }

        $gender = $this->request->post('gender');
//        $bio = $this->request->post('bio');
        if (!$avatar && !$nickname && !$gender) {
            $this->error(__('Invalid parameters'));
        }
        $user = $this->auth->getUser();
        if ($avatar){
            $user->avatar = $avatar;
        }
        if ($nickname){
            $user->nickname = $nickname;
        }
        if ($gender){
            $user->gender = $gender;
        }
        if($user->save()){
            //同步im的后台数据
            //先判断当前用户是不是咨询师，如果是咨询师不用同步
            $zxs = Db::name('mental_xlzxinfo')->where(['user_id'=>$this->auth->id,'status'=>1])->find();
            if(empty($zxs)){
                $usertoken = Ims::update_user_check($this->auth->id);
            }
        };
        //修改成功的事件
        Hook::listen("user_update_profile", $user);
        $this->success(__('Operation completed'), ['userinfo' => $this->auth->getUserinfo()]);
    }

    /**
     * Undocumented function
     * 公众号授权【已手机登录，未微信授权，在支付时的登录】
     * @return void
     */
    public function getopenid()
    {
        $code = $this->request->post('code');
        $scope = $this->request->post('scope');  //公众号登陆类型，1是snsapi_userinfo，2是snsapi_base
        $state = $this->request->post('state');
        if (!$code || !$scope || !$state) {
            $this->error(__('Invalid parameters'));
        }
        $wechat = new \addons\mental\library\Wechat;
        $result = $wechat->codeToInfo($code, $state, $scope, $this->auth->id);
        if ($result['status']) {
            $this->success(__('Operation completed'));
        } else {
            $this->error(__('Operation failed'));
        }
    }

    //公众号授权登录【未手机登录的，在微信的登录】
    public function authLogin()
    {
        $code = $this->request->post('code');
        $scope = $this->request->post('scope');  //公众号登陆类型，1是snsapi_userinfo，2是snsapi_base
        $state = $this->request->post('state');
        if (!$code || !$scope || !$state) {
            $this->error(__('Invalid parameters'));
        }
        $wechat = new \addons\mental\library\Wechat;
        $result = $wechat->codeToInfo($code, $state, $scope);
        if ($result['status']) {
            //存在用户id
            $wx_user = $result['data'];

            if ($wx_user['user_id']) {
                $this->auth->direct($wx_user['user_id']);
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            }
            //如果未开启手机号码绑定，直接创建账号登录
            if (Config::get('mental.is_bind_mobile') == 1) {
                $username = Random::alnum(20);
                $password = Random::alnum(6);
                $domain = request()->host();
                $ret = $this->auth->register($username, $password, $username . '@' . $domain, '', [
                    'nickname' => $wx_user['nickname'],
                    'avatar' => $wx_user['avatar']
                ]);
                if (!$ret) {
                    $this->error($this->auth->getError());
                }
                $wxUserModel = new WxUser();
                $wxUserModel->where('id', $wx_user['id'])->update(['user_id' => $this->auth->id]);
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            }
            Session::set('wx_user_id', $wx_user['id']);
            $this->success('请绑定手机号码', 100);
        } else {
            $this->error($result['msg'] ?? '操作失败');
        }
    }
}
